<template>
    <div>
        <div>
            <van-nav-bar title="资产盘盈" @click-left="onClickLeft" left-arrow />
        </div>
        <div style="width: 95vw; margin: 10px auto;">
            <card mode="py" :taskId="taskId" ref="cardref" :cardList="cardList" :Objapi="Objapi" @cardItem="getItem" @formChange="onFormChange"></card>
        </div>
    </div>
</template>

<script>
import card from './components/card.vue';
import backMixin from '../../mixins/backMixin'

export default {
    mixins: [backMixin],
    components: {
        card,
    },
    data() {
        return {
            cardList: [
                {
                    name: '资产名称',
                    value: 'profitPropertyName',
                    key: 'zcmc',
                    icon: ''
                },
                {
                    name: '管理单位',
                    value: 'profitOrgName',
                    key: 'gldw',
                    icon: ''
                }, 
                {
                    name: '资产类型',
                    value: 'profitTypeName',
                    key: 'zclx',
                    icon: ''
                }, 
                {
                    name: '所属项目',
                    value: 'profitProjectName',
                    key: 'ssxm',
                    icon: ''
                },
                {
                    name: '补充说明',
                    value: 'remark',
                    key: 'bcsm',
                    icon: ''
                },
                {
                    name: '相关附件',
                    value: '',
                    key: 'xgfj',
                    icon: ''
                },
            ],
            form: {},
            Objapi: this.$api.stocktaking, //盘盈
            orgTree: null,
            projectTree: null,
            propertyTypeTree: null,
            taskId: null,
        }
    },
    computed: {
        // 监听Vuex中的资产信息变化
        assectInfo() {
            return this.$store.state.assectData.assectInfo || {}
        }
    },
    watch: {
        // 监听assectInfo变化，当从编辑页面跳转过来时更新表单
        assectInfo: {
            handler(newVal) {
                console.log('assectInfo changed in assectProfit:', newVal)
                if (newVal && Object.keys(newVal).length > 0) {
                    this.updateFormData(newVal)
                }
            },
            deep: true,
            immediate: true
        }
    },
    mounted() {
        console.log('assectProfit mounted')
        this.initializeData()
    },
    activated() {
        console.log('assectProfit activated')
        this.handleBackDataFromRoute()
    },
    async created() {
        await this.loadAllTreeData()
    },
    methods: {
        // 初始化数据
        initializeData() {
            const id = this.$route.query.taskId
            this.taskId = id
            console.log('Task ID from route:', id)
            
            // 处理回退数据
            this.handleBackDataFromRoute()
            
            // 如果有Vuex中的数据，使用它
            if (this.assectInfo && Object.keys(this.assectInfo).length > 0) {
                console.log('Using assectInfo from Vuex:', this.assectInfo)
                this.updateFormData(this.assectInfo)
            } else {
                console.log('No assectInfo found in Vuex')
            }
        },
        
        // 根据名称在树结构中查找ID
        findIdByName(treeData, name, idField = 'nodeId', nameField = 'nodeName') {
            if (!treeData || !name) return null
            
            const findInTree = (node) => {
                if (!node) return null
                
                // 检查当前节点
                if (node[nameField] === name) {
                    return node[idField] || null
                }
                
                // 检查子节点
                if (node.childList && Array.isArray(node.childList)) {
                    for (const child of node.childList) {
                        const found = findInTree(child)
                        if (found) return found
                    }
                }
                
                // 检查children字段（备用）
                if (node.children && Array.isArray(node.children)) {
                    for (const child of node.children) {
                        const found = findInTree(child)
                        if (found) return found
                    }
                }
                
                return null
            }
            
            // 处理数组或单个节点
            if (Array.isArray(treeData)) {
                for (const node of treeData) {
                    const found = findInTree(node)
                    if (found) return found
                }
            } else {
                return findInTree(treeData)
            }
            
            return null
        },
        
        // 更新表单数据 - 修复字段映射和ID查找
        async updateFormData(data) {
            console.log('Updating form data with:', data)
            
            // 创建新的表单对象，确保包含所有需要的字段
            // 特别注意：资产名称字段映射
            this.form = {
                // 资产名称映射：editTask中的name -> assectProfit中的profitPropertyName
                profitPropertyName: data.propertyName || '',
                
                // 其他字段映射
                profitOrgName: data.orgName || data.profitOrgName || '',
                profitTypeName: data.typeName || data.profitTypeName || '',
                profitProjectName: data.projectName || data.profitProjectName || '',
                remark: data.remark || '',
                
                // ID字段映射 - 如果有ID直接使用，否则根据名称查找
                profitOrgId: data.orgId || data.profitOrgId || '',
                profitTypeId: data.typeId || data.profitTypeId || '',
                profitProjectId: data.projectId || data.profitProjectId || '',
                
                // 保留原始数据中的其他字段
             //   ...data
            }
            
            console.log('Form before ID lookup:', this.form)
            
            // 如果缺少ID，根据名称从对应的树结构中查找
            if (this.form.profitOrgId=='' || this.form.profitOrgId==null) {
                const orgId = this.findIdByName(this.orgTree, this.form.profitOrgName, 'nodeId', 'nodeName')
                console.log('orgTree for lookup:', this.form.profitOrgName,this.orgTree)
                if (orgId) {
                    this.form.profitOrgId = orgId
                    console.log('Found orgId by name:', orgId)
                }
            }
            
            if (!this.form.profitTypeId && this.form.profitTypeName && this.propertyTypeTree) {
                const typeId = this.findIdByName(this.propertyTypeTree, this.form.profitTypeName, 'id', 'name')
                if (typeId) {
                    this.form.profitTypeId = typeId
                    console.log('Found typeId by name:', typeId)
                }
            }
            
            if (!this.form.profitProjectId && this.form.profitProjectName && this.projectTree) {
                const projectId = this.findIdByName(this.projectTree, this.form.profitProjectName, 'nodeId', 'nodeName')
                if (projectId) {
                    this.form.profitProjectId = projectId
                    console.log('Found projectId by name:', projectId)
                }
            }
            
            console.log('Form after ID lookup:', this.form)
            console.log('资产名称字段值:', this.form.profitPropertyName)
            
            // 更新card组件
            this.updateCardForm()
        },
        
        // 更新card组件表单
        updateCardForm() {
            this.$nextTick(() => {
                if (this.$refs.cardref && typeof this.$refs.cardref.setformdata === 'function') {
                    console.log('Calling cardref.setformdata with:', this.form)
                    this.$refs.cardref.setformdata(this.form)
                } else {
                    console.warn('cardref not found or setformdata method not available')
                }
            })
        },
        
        async loadAllTreeData() {
            try {
                await Promise.all([this.getorgProjectTree(), this.getorgPropertyType(), this.getorgTree()])
            } catch (error) {
                console.error('加载树结构数据失败:', error)
            }
        },
        
        async getorgProjectTree() {
            try {
                const res = await this.$Geting(this.$api.getorgProjectTree)
                if (res.code === '0') {
                    this.projectTree = res.data.treeData
                    this.$store.commit('assectData/setProjectTree', this.projectTree)
                    console.log('项目树加载完成:', this.projectTree)
                } else {
                    this.$toast(res.message)
                }
            } catch (err) {
                console.error('获取项目树出错', err)
            }
        },
        
        async getorgTree() {
            try {
                const res = await this.$Geting(this.$api.getorgTree)
                if (res.code === '0') {
                    this.orgTree = res.data.treeData
                    this.$store.commit('assectData/setorgTree', this.orgTree)
                    console.log('组织树加载完成:', this.orgTree)
                } else {
                    this.$toast(res.message)
                }
            } catch (err) {
                console.error('获取管理单位树出错', err)
            }
        },
        
        async getorgPropertyType() {
            try {
                const res = await this.$Geting(this.$api.getorgPropertyType)
                if (res.code === '0') {
                    this.propertyTypeTree = res.data
                    this.$store.commit('assectData/setpropertyTypeTree', this.propertyTypeTree)
                    console.log('资产类型树加载完成:', this.propertyTypeTree)
                } else {
                    this.$toast(res.message)
                }
            } catch (err) {
                console.error('获取资产类型树出错', err)
            }
        },
        
        // 处理 card 组件点击事件
        getItem(item) {
            // 这里只做占位，跳转已在 card 组件内部处理
            console.log('Card item clicked:', item)
        },
        
        onFormChange({ key, value }) {
            // 将子组件输入同步到父组件的 form 中，确保在路由回填时保留用户已输入的字段
            console.log('Form change:', key, value)
            this.$set(this.form, key, value)
        },
        
        // 将来自选择页的 backData 解析成统一格式数组 [{ id, text, mode }]
        normalizeBackData(raw) {
            let parsed = raw
            if (typeof raw === 'string') {
                try {
                    parsed = JSON.parse(raw)
                } catch (e) {
                    // 如果解析失败，保留原始字符串（下方会忽略）
                    parsed = raw
                }
            }

            const toItem = (item) => {
                if (!item || typeof item !== 'object') return null
                const id = item.projectId ?? item.typeId ?? item.memberId ?? item.orgId ?? item.id ?? item.value ?? ''
                const text = item.projectName ?? item.typeName ?? item.memberName ?? item.orgName ?? item.text ?? item.name ?? ''
                let mode = ''
                if (item.projectId) mode = 'ssxm'
                else if (item.typeId) mode = 'zclx'
                else if (item.memberId) mode = 'zrr'
                else if (item.orgId) mode = 'gldw'
                // 只要有 id 或 text 就认为是有效项
                return (id !== '' || text !== '') ? { id, text, mode } : null
            }

            if (Array.isArray(parsed)) {
                return parsed.map(toItem).filter(Boolean)
            }

            if (parsed && typeof parsed === 'object') {
                const it = toItem(parsed)
                return it ? [it] : []
            }

            return []
        },

        // 处理路由回传的 backData，直接回填到本页表单并清理 query
        handleBackDataFromRoute() {
            console.log('handleBackDataFromRoute called')
            
            // 优先从 Vuex 读取返回数据，其次兼容路由 query.backData
            let backData = null
            try {
                backData = this.$store && this.$store.state && this.$store.state.assectData && this.$store.state.assectData.returnData
                if (backData != null) {
                    console.log('Found backData in Vuex:', backData)
                    try { 
                        this.$store.commit('assectData/setReturnData', null) 
                    } catch (e) { 
                        console.log('Clear returnData failed:', e)
                    }
                }
            } catch (err) {
                backData = null
            }
            
            if (backData == null) {
                backData = this.$route.query.backData
                console.log('Checking route query backData:', backData)
            }
            
            if (!backData) {
                console.log('No backData found')
                return
            }

            const normalized = this.normalizeBackData(backData)
            console.log('Normalized backData:', normalized)
            
            if (normalized && normalized.length) {
                const first = normalized[0]
                if (first.mode === 'ssxm') {
                    this.form.profitProjectId = first.id
                    this.form.profitProjectName = first.text
                } else if (first.mode === 'zclx') {
                    this.form.profitTypeId = first.id
                    this.form.profitTypeName = first.text
                } else if (first.mode === 'gldw') {
                    this.form.profitOrgId = first.id
                    this.form.profitOrgName = first.text
                }

                console.log('Form after backData:', this.form)
                
                // 回填 UI
                this.updateCardForm()
            }

            // 清理路由 query，避免重复处理
            try { 
                this.$router.replace({ query: {} }) 
            } catch (e) { 
                console.log('Clear query failed:', e)
            }
        },
        
        onClickLeft() {
            console.log('Navigate back clicked')
            // 清理Vuex中的数据
            try {
                this.$store.commit('assectData/setAssectInfo', {})
            } catch (e) {
                console.log('Clear assectInfo failed:', e)
            }
            
            // 使用统一的返回逻辑
            this.navigateBack()
        }
    }
}
</script>

<style scoped></style>